package com.gopay.bis.web.controller.util;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * 
 * @Description xml-bean转换
 * @date 2015年11月23日
 * @author jiangxiangjiao
 *
 */
public class XmlBeanUtil {
	
	// 去掉多一个下划线的问题
	private static XStream xstream = new XStream(new DomDriver("UTF-8", new NoNameCoder()));
	
	private XmlBeanUtil(){
		
	}

	/**
	 * 将JAVA对象转换成请求的XML报文
	 * @param obj 被转换的java对象
	 * @param bodyCla java对象的body属性对应的类型
	 */
	public static  String toXml(Object obj,Class bodyCla) {
		xstream.processAnnotations(obj.getClass());
		xstream.addDefaultImplementation(bodyCla, Object.class);
		xstream.alias("merchant", obj.getClass());
		return xstream.toXML(obj);
	}
	

	/**
	 * 将响应报文转换成Java对象
	 * @param xmlStr
	 * @param cls xml对应的class类
	 * @param bodyCla xml报文的body节点对应的class
	 * @return T xml对应的class类的实例对象
	 */
	public static <T> T toBean(String xmlStr, Class<T> cls,Class bodyCla) {
		xstream.processAnnotations(cls);
		xstream.addDefaultImplementation(bodyCla, Object.class);
		xstream.alias("message",cls);
		T obj = (T) xstream.fromXML(xmlStr);
		return obj;
	}
}
